import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";

import download from "@/utils/download";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import { FormattedMessage } from "umi-plugin-react/locale";
import { Row, Col, Card, Icon, Form, Spin, Tag, Table, Input, Button, message, Modal, Upload, Tooltip, Pagination } from "antd";
import styles from "./index.less";
import axios from "axios";
import deleteimg from "@/assets/buttonimg/delete.png";
const FormItem = Form.Item;
const { TextArea } = Input;
const Search = Input.Search;
const MyIcon = Icon.createFromIconfontCN({
	scriptUrl: "//at.alicdn.com/t/font_1131883_m18hmgbwet.js", // 在 iconfont.cn 上生成
});
import pen from "../../../assets/icons/bi.png";
import EditTag from "@/pages/BasicCapacity/ThesaurusManage/editTag";
import { getAuthority } from "@/utils/judgeAuthority";
import importIcon from "@/assets/importIcon.png";
import exportIcon from "@/assets/exportIcon.png";
import tableDataCheck from "@/utils/isBackPrevPage";
import UserSession from "@/UserSession";

class ThesaurusManage extends Component {
	constructor(props) {
		super(props);
		this.state = {
			dataSource: [],
			formatA: "",
			formatB: "",
			pageSize: 10,
			page: 1,
			value: "",
			total: 0,
			fileList: [],
			uploading: false,
			editTags: [],
			id: null,
		};
	}

	// eslint-disable-next-line react/sort-comp
	fetch = (query, page = 1, limit = 10) => {
		this.setState({ login: true, dataSource: [] });
		const { dispatch, currentUser } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "thesaurusManage/fetch",
				payload: {
					search: query,
					current: page,
					size: limit,
				},
				callback: (res) => {
					let temp = res.records;
					temp.map((item, index) => (item["key"] = index));
					this.setState({
						login: false,
						dataSource: temp,
						total: res.total,
					});
				},
			});
		});
	};

	componentDidMount() {
		this.fetch();
	}

	lessdata = () => {
		const columns1 = [
			{
				title: <FormattedMessage id='app.customDictionary.core-word' defaultMessage='coreWord' />,
				width: "15%",
				dataIndex: "word",
			},
			{
				title: <FormattedMessage id='app.customDictionary.core-agreed' defaultMessage='agreed' />,
				width: "60%",
				dataIndex: "wordsSyn",
				render: (aligns) => {
					return (
						<div style={{ display: "flex", flexWrap: "wrap", }}>
							{aligns.map((tag, index) => {
								let color = index % 2 == 1 ? "#87d3ac" : "#5092e1";
								return (
									<Tag style={{ marginBottom: 2, wordBreak: "break-all" }} color={color} key={tag}>{tag}</Tag>
								);
							})}
						</div>
					);
				},
			},
			{
				title: <FormattedMessage id='app.customDictionary.operation' defaultMessage='operation' />,
				dataIndex: "sex",
				width: "10%",
				render: (text, item) => {
					return (
						<div className={styles.pb}>
							<Button
								size='small'
								icon='edit'
								type={"primary"}
								disabled={getAuthority(this.props.route.authority) === 1}
								onClick={(text) => {
									this.handleDeleteA(item);
								}}
								style={{ marginRight: 10 }}
							>
								<FormattedMessage id='app.customDictionary.edit' defaultMessage='Edit' />
							</Button>
							<Button
								size='small'
								icon='delete'
								type={"danger"}
								disabled={getAuthority(this.props.route.authority) === 1}
								onClick={(text) => {
									this.fromDeletes(item);
								}}
							>
								<FormattedMessage id='app.customDictionary.out' defaultMessage='out' />
							</Button>
						</div>
					);
				},
			},
		];

		return (
			<Spin spinning={this.state.login}>
				<Table
					className='zdyTable'
					columns={columns1}
					dataSource={this.state.dataSource} // 数据
					onChange={this.handleChange}
					pagination={false}
				/>
				{this.state.total > 10 ? (
					<Pagination
						style={{ textAlign: 'right', marginTop: 16 }}
						total={this.state.total}
						pageSize={this.state.pageSize}
						current={this.state.page}
						// showSizeChanger={true}
						showQuickJumper={true}
						onChange={this.onChange}
						// onShowSizeChange={this.onShowSizeChange}
					/>
				) : null}
			</Spin>
		);
	};

	handleDeleteA = (item) => {
		this.setState({
			formatC: item.word,
			formatA: item.word,
			formatB: item.wordsSyn.join(","),
			showModel2: true,
			editTags: item.wordsSyn,
			id: item.id,
		});
	};

	fromDeletes = (item) => {
		Modal["confirm"]({
			title: "删除任务",
			content: "确定删除吗？",
			okText: "删除",
			cancelText: "取消",
			onOk: () => {
				const { dispatch, currentUser } = this.props;
				this.reqRef = requestAnimationFrame(() => {
					dispatch({
						type: "thesaurusManage/fetchc",
						payload: { id: item.id },
						callback: (res) => {
							//判断是否需要加载上一页数据 2022.4.8
							const { dataSource, page } = this.state;
							const newCurrent = tableDataCheck(dataSource, page);
							this.setState({ page: newCurrent, });
							this.fetch(this.state.value, newCurrent, this.state.pageSize);
							message.info(`${res.message}`);
						},
					});
				});
			},
			onCancel() { },
		});
	};

	onChange = (val) => {
		// 页数选择
		this.setState({ page: val });
		this.fetch(this.state.value, val, this.state.pageSize);
	};

	onShowSizeChange = (val, pageSize) => {
		this.fetch(this.state.value, val, pageSize);
		this.setState({ pageSize, page: val });
	};

	leadWay = () => {
		this.setState({ showModelA: true, fileList: [] });
	};

	impTemp = () => {
		const { dispatch, currentUser } = this.props;
		dispatch({
			type: "thesaurusManage/fetchd",
			payload: {},
			callback: (res) => {
				let filename = decodeURIComponent(res.requestRes.headers.get("Content-Disposition").split("=")[1]);
				download.byBlob(res.fileBlob, filename);
			},
		});
	};

	handleUpFile = (info) => {
		let fileList = [...info.fileList];
		fileList = fileList.slice(-1);
		fileList = fileList.map((file) => {
			if (file.response) {
				file.url = file.response.url;
			};
			return file;
		});
		if (fileList[0].size / 1024 / 1024 > 2) {
			// 2000000
			message.error("上传文件超出2M");
			this.setState({ fileList: [] });
		} else {
			this.setState({ fileList });
		}
	};

	uploadFile = (data) => {
		const { dispatch } = this.props;
		dispatch({
			type: "thesaurusManage/synonymimport",
			payload: data,
			callback: (res) => {
				this.setState({ uploading: false, }, () => {
					if (res.data.code) {
						return message.error(res.data.msg);
					} else {
						this.setState({ showModelA: false, visible: false, fileList: [], page: 1, }, () => {
							this.fetch();
							if (res.data.msg) {
								message.success(res.data.msg);
							} else {
								message.success("导入成功");
							}
						});
					}
				});
			},
		});
	};

	businessWayA = () => {
		const { fileList } = this.state;
		const formData = new FormData();
		fileList.forEach((file) => {
			formData.append("file", file.originFileObj);
		});
		this.setState({ uploading: true, });
		this.uploadFile(formData);
	};

	handleCancel = () => {
		this.setState({ showModelA: false, uploading: false, fileList: [] });
	};

	answerDetail = () => {
		// fetche
		const { initialValue } = this.state;
		if (this.state.total === 0) {
			message.error("空列表无法导出！");
		} else {
			const { dispatch, currentUser } = this.props;
			dispatch({
				type: "thesaurusManage/fetche",
				payload: { query: initialValue },
				callback: (res) => {
					let filename = decodeURIComponent(res.requestRes.headers.get("Content-Disposition").split("=")[1]);
					download.byBlob(res.fileBlob, filename);
				},
			});
		}
	};

	render() {
		const { getFieldDecorator } = this.props.form;
		const FormItemLayont = {
			labelCol: {
				// 文字
				xs: 24,
				sm: 4,
			},
			wrapperCol: {
				// 输入框
				xs: 24,
				sm: 20,
			},
		};
		const { uploading, fileList } = this.state;
		// const headData = { "token": JSON.parse(window.localStorage.getItem("currentUser")).token };
		const props = {
			// name: 'file',
			// headers: headData,
			// action: '/basic/synonym/import',
			// accept: '.xlsx',
			// onChange: this.handleChangeByUpload,
			onRemove: (file) => {
				this.setState((state) => {
					const index = state.fileList.indexOf(file);
					const newFileList = state.fileList.slice();
					newFileList.splice(index, 1);
					return { fileList: newFileList, };
				});
			},
			beforeUpload: (file) => {
				this.setState((state) => ({ fileList: [...state.fileList, file], }));
				return false;
			},
			accept: ".xlsx,.xls",
			fileList,
			onChange: this.handleUpFile,
		};
		const { route } = this.props;

		return (
			<Suspense fallback={<PageLoading />}>
				<PageHeaderWrapper>
					<Card bordered={false} style={{ height: '100%' }} bodyStyle={{ height: '100%', padding: 0 }}>
						<Row className={styles.colorBackground}>
							<Col style={{ padding: 10, color: "#4B5475", fontWeight: 600 }} xs={24}>
								<div className={styles.title}>
									<span>同义词管理{`(${this.state.total})`}</span>
									<span style={{ marginLeft: 2, paddingTop: 2 }}>
										<Tooltip
											placement='top'
											title='增加同义词是为了帮助机器人更好的识别聊天的问题描述，减少错别字、同义字、词、
                    句对机器人的影响，同时有效地减少类似句式同义句的编写。在这里添加的每一组同义词将在所有知识点中生效。
                    如库内有句子“我要办理易分期”，且已经把“医分期”设为“易分期”的同义词，当用户问“我要办理医分期”时，将会生效，回复正确答案。'
											arrowPointAtCenter
										>
											<Icon type='info-circle' />
										</Tooltip>
									</span>
								</div>
							</Col>
						</Row>
						<Card bordered={false}>
							<div className={styles.fromColumn}>
								<span style={{ display: 'inline-flex', alignItems: 'center', gap: 16 }}>
									{getFieldDecorator("coreword11", { initialValue: this.state.value, })(
										<Input
											placeholder='请输入搜索词'
											onSearch={e => this.setState({ value: e.target.value })}
											style={{ width: 323 }}
										/>
									)}
									<Button type="primary" onClick={() => this.setState({ page: 1, }, () => this.fetch(value, this.state.page, this.state.pageSize))}>查询</Button>
								</span>
								<span className={styles.right}>
									<span className='buttonYs'>
										<Button onClick={this.enumeration} disabled={getAuthority(route.authority) === 1} type="primary">新增</Button>
									</span>
									<span className='buttonYs'>
										<Button onClick={this.leadWay}>导入</Button>
									</span>
									<span className='buttonYs'>
										<Button onClick={this.answerDetail}>导出</Button>
									</span>
								</span>
							</div>
							{this.lessdata()}
						</Card>
						<Modal
							className='modelZdy'
							title='添加/编辑同义词'
							visible={this.state.showModel2}
							okText={<FormattedMessage id='app.customDictionary.save' />}
							cancelText={<FormattedMessage id='app.customDictionary.cancel' />}
							onCancel={() => {
								this.setState({ showModel2: false, editTags: [], id: null, });
							}}
							onOk={this.coreWord} // 确定方法开出去
							destroyOnClose
						>
							<Form layout='horizontal'>
								<FormItem
									label={<FormattedMessage id='app.customDictionary.core-word' />}
									onSubmit={this.coreWord}
									{...FormItemLayont}
								>
									{getFieldDecorator("coreword", {
										initialValue: this.state.formatA,
										rules: [
											{ required: true, message: "核心词不能为空" },
											(rule, value = "", callback) => {
												try {
													if (value.length > 20) {
														callback("核心词不可超过20个字符");
													};
													callback();
												} catch (err) {
													callback(err);
												}
											},
										],
									})(<Input />)}
								</FormItem>
								<FormItem
									label={<FormattedMessage id='app.customDictionary.core-agreed' />}
									style={{ display: 'flex', alignItems: 'center' }}
									{...FormItemLayont}
								>
									{getFieldDecorator("synonym")(
										<EditTag onRef={(ref) => (this.EditTag = ref)} tags={this.state.editTags} />
									)}
								</FormItem>
							</Form>
						</Modal>

						<Modal
							className='modelZdy'
							width={550}
							title='上传同义词'
							visible={this.state.showModelA}
							footer={[
								<Button key='back' onClick={this.handleCancel}>取消</Button>,
								<Button key='submit' type='primary' loading={uploading} disabled={fileList.length === 0} onClick={this.businessWayA}>{uploading ? "导入中" : "开始导入"}</Button>,
							]}
							onCancel={() => {
								this.setState({ showModelA: false, uploading: false });
							}}
						>
							<Form layout='horizontal'>
								<FormItem label='选择文件' onSubmit={this.coreWordOne} {...FormItemLayont}>
									<Upload {...props} fileList={this.state.fileList}>
										<Button> <Icon type='upload' /> 选择文件 </Button>
									</Upload>
								</FormItem>
								<FormItem label='上传规则' onSubmit={this.coreWordOne} {...FormItemLayont}>
									<div className={styles.frame}>
										<div>
											<span>• 请按照模板中的示例格式进行编辑上传：</span>{" "}
											<span onClick={this.impTemp} className={styles.template}>下载xls模版</span>
										</div>
										<div>
											<span>• 上传文件格式需要为“.xls”类型的Excel文件</span>
										</div>
										<div>
											<span>• 导入的同义词数据将覆盖现有数据，请谨慎操作</span>
										</div>
									</div>
								</FormItem>
							</Form>
						</Modal>
					</Card>
				</PageHeaderWrapper>
			</Suspense>
		);
	}

	qukong = (val) => {
		var arr = [];
		val.map(function (val, index) {
			if (val !== "" && val != undefined) {
				arr.push(val);
			}
		});
		return arr;
	};

	coreWord = () => {
		this.setState({ value: "" });
		this.props.form.setFields({ coreword11: "" });
		let userInfo = this.props.form.getFieldsValue(); // 获取数据
		this.props.form.validateFields((err, values) => {
			// 校验方法formatA
			if (!err) {
				if (userInfo.coreword !== "") {
					let ok = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(userInfo.coreword);
					var synonym = this.EditTag.state.tags;
					const checkSynonym = this.EditTag.state.checkValue;
					if (!checkSynonym.state) {
						return message.error({ content: "同义词不可超过20个字符", key: "synonym", });
					};
					const { dispatch, currentUser } = this.props;
					let obj = {
						synWords: this.qukong(synonym),
						word: userInfo.coreword,
					};
					let url = "thesaurusManage/fetchb";
					if (this.state.id) {
						obj.id = this.state.id;
						url = "thesaurusManage/fetchWordEdit";
					};
					this.reqRef = requestAnimationFrame(() => {
						dispatch({
							type: url,
							payload: obj,
							callback: (res) => {
								if (typeof res.code !== 'undefined' && res.code !== 0) {
									// message["error"](`${res.message}`);
								} else {
									this.setState({ showModel2: false, editTags: [], id: null });
									this.props.form.setFields({ coreword: "" });
									message.info(`${res.message}`);
									this.fetch(this.state.value, this.state.page, this.state.pageSize);
								}
							},
						});
					});
				} else {
					message["warning"](`请添加核心词`);
				}
			}
		});
	};

	// 回车事件
	coreWords = (e) => {
		this.setState({ value: "" });
		this.props.form.setFields({ coreword11: "" });
		let userInfo = this.props.form.getFieldsValue(); // 获取数据
		this.props.form.validateFields((err, values) => {
			// 校验方法formatA
			if (!err) {
				let ok = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(userInfo.coreword);

				if (userInfo.coreword !== "") {
					if (ok) {
						var str = e.target.value;

						var arr = new Array();
						arr = str.split(/[,，]/);

						const { dispatch, currentUser } = this.props;
						this.reqRef = requestAnimationFrame(() => {
							dispatch({
								type: "thesaurusManage/fetchb",
								payload: {
									aligns: arr,
									oldWord: this.state.formatA,
									word: userInfo.coreword,
									robotId: currentUser.robotId,
								},
								callback: (res) => {
									if (res.code === 0) {
										this.setState({ showModel2: true, });
										this.props.form.setFields({ coreword: "" });
										this.props.form.setFields({ synonym: "" });
									} else {
										this.setState({ showModel2: true, });
									};
									if (res.code === 0) {
										message.success(`${res.msg}`);
										this.fetch(this.state.value, this.state.page, this.state.pageSize);
									}
								},
							});
						});
					} else {
						message["warning"](`同义词仅支持汉字、数字和字母 `);
					}
				} else {
					message["warning"](`请添加核心词`);
				}
			}
		});
	};

	enumeration = () => {
		this.setState({ formatA: "", formatB: "", editTags: [], showModel2: true, });
	};
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(ThesaurusManage));
